package demo.mina;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * Hello world!
 *
 */
public class MinaTimeServer
{
    public static void main( String[] args ) throws IOException {
        new MinaTimeServer().start();
    }

    public void start() throws IOException {
        //创建一个服务端监听器
        IoAcceptor socketAcceptor = new NioSocketAcceptor();
        //添加过滤链
        socketAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
        //设置协议解析过滤器
        socketAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(StandardCharsets.UTF_8)));
        socketAcceptor.setHandler(new TimeServerHandler());
        //设置缓冲区大小和空闲属性
        socketAcceptor.getSessionConfig().setReadBufferSize(2048);
        socketAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

        socketAcceptor.bind(new InetSocketAddress(9123));
    }


    public static class TimeServerHandler extends IoHandlerAdapter {

        /**
         * 捕获异常的方法
         * @param session
         * @param cause
         * @throws Exception
         */
        @Override
        public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
            cause.printStackTrace();
        }

        /**
         * 接收消息处理
         * @param session
         * @param message 根据指定的协议解码器，出入这里的对象就是不同的类型，如果不指定协议解码器，会收到一个IoBuffer
         * @throws Exception
         */
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            String s = message.toString();
            if (s.trim().equals("quit")) {
                session.closeNow();
                return;
            }
            Date date = new Date();
            session.write(date.toString());
            System.out.println("Message written......");
        }

        /**
         * 一旦在 socketAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); 中指定的时间内保持空闲状态，就会调用当前方法
         * @param session
         * @param status
         * @throws Exception
         */
        @Override
        public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            System.out.println("IDLE" + session.getIdleCount(status));
        }


    }

}
